<%@ page contentType="text/html; charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" href="${ctxStatic}/jsPlumb//css/jsplumb.css">
	<link rel="stylesheet" href="${ctxStatic}/jsPlumb/myJsPlumb.css">
	<title>流程配置</title>
	<meta name="decorator" content="default"/>
	<script src="${ctxStatic}/jsPlumb/jquery-1.9.0-min.js"></script>
	<script src="${ctxStatic}/jsPlumb/jquery-ui-1.9.2.min.js"></script>
	<script src="${ctxStatic}/jsPlumb/jquery.ui.touch-punch-0.2.2.min.js"></script>
	<script src="${ctxStatic}/jsPlumb/jquery.jsPlumb-1.7.5.js"></script>
</head>
<body>
	<%@ include file="/WEB-INF/views/modules/euler/eulerNav.jsp" %>
	<div class="container-fluid">
		<div class="row-fluid">
			<div class="span3">
				<form id="SaveForm">
				  <fieldset>
				    <legend>流程属性</legend>
				    <label>流程名称:</label>
				    <input type="text" id="flowName" name="flowName" value="" placeholder="流程名称"/>
				    <br/>
				    <label>操作:</label>
				    <input id="btnSave" type="button" class="btn btn-primary" value="保存流程" />
				  </fieldset>
				</form>
				<form id="LoadForm">
				  <fieldset>
				    <legend>加载流程</legend>
				    <label>流程对象:</label>
				    <textarea id="flowObj" name="flowObj" value="" placeholder="流程对象" rows="10"></textarea>
				    <br/>
				    <label>操作:</label>
				    <input id="btnLoad" type="button" class="btn btn-primary" value="加载流程" />
				  </fieldset>
				</form>
			</div>
			<div class="span9">
				<div id="main">
					<div class="demo statemachine-demo" id="statemachine-demo">
			        	<div class="d" id="ccc">
			        		<span>起点</span>
			            	<div class="ep"></div>
			        	</div>
			        	<div class="d" id="ddd">
			        		<span>终点</span>
			            	<div class="ep"></div>
			        	</div>
			    	</div>
			    </div>
		    </div>
	    </div>
    </div>
    <script type="text/javascript">
    	jsPlumb.ready(function(){
    		// 全局ID唯一标识；
    		window.id = 1;
    		// 初始化实例；
    		var firstInstance = getInstance();
    		
    		// 设置组建可以拖拽创建；
		    $( "#ccc" ).draggable({
	    		appendTo: "#statemachine-demo",
	    		helper: "clone",
	    		stop: function( event, ui ) {
	    			var data = {};
	    			// 设置newID；
	    			var newId = window.id++;
					data['id'] = newId;
					// 设置位置信息；
	    			var a = ui["helper"][0];
	    			var b = $(a).clone(true);
					data['left'] = $(b).css("left");
					data['top'] = $(b).css("top");
					eulerCreateEndPoint(firstInstance, data, b);
	    		}
	    	});
    		
		    $( "#ddd" ).draggable({
	    		appendTo: "#statemachine-demo",
	    		helper: "clone",
	    		stop: function( event, ui ) {
	    			var data = {};
	    			// 设置newID；
	    			var newId = window.id++;
					data['id'] = newId;
					// 设置位置信息；
	    			var a = ui["helper"][0];
	    			var b = $(a).clone(true);
					data['left'] = $(b).css("left");
					data['top'] = $(b).css("top");
					eulerCreateEndPoint(firstInstance, data, b);
	    		}
	    	});
    		
			// 添加新联系
			function eulerCreateConnect (firstInstance, data) {
				sourceId = data.sourceId;
				targetId = data.targetId;
				console.log(typeof targetId);
				firstInstance.connect({ source: sourceId, target: targetId });
			}
			
    		// 添加新元素
			function eulerCreateEndPoint (firstInstance, data, template) {
				var newId = data.id;
				var left = data.left;
				var top   = data.top;
				var b = template;
				var spanText = $($($(b)[0]).find("span")[0]).text();
				$($($(b)[0]).find("span")[0]).text(newId + spanText);
				var newDiv = $(b).html();
    			$("#statemachine-demo").append($("<div class=\"w\" id=\""+newId+"\"></div>").append(newDiv));
				$("#"+newId).css("left", left);
				$("#"+newId).css("top", top);
    			firstInstance.makeSource($("#"+newId), {
			            filter: ".ep",
			            anchor: "Continuous",
			            connector: [ "StateMachine", { curviness: 20 } ],
			            connectorStyle: { strokeStyle: "#5c96bc", lineWidth: 2, outlineColor: "transparent", outlineWidth: 4 },
			            maxConnections: 5,
			            onMaxConnections: function (info, e) {
			                alert("Maximum connections (" + info.maxConnections + ") reached");
			            }
				});
		        firstInstance.makeTarget($("#"+newId), {
					dropOptions: { hoverClass: "dragHover" },
					anchor: "Continuous",
					allowLoopback: true
				});
	
				firstInstance.draggable($("#"+newId));
				editable($("#"+newId));
				removable($("#"+newId));
			}
    		
    		// 保存流程；
    		$("#btnSave").click(function() {
    			event.preventDefault();
    			var workFlowData = {};
    			var resultEndPoints = getEndPoints();
    			var resultContions  = getConnections();
    			workFlowData['endPoints'] = resultEndPoints;
    			workFlowData['contions'] = resultContions;
    			// 获取流程名称
    			var flowName = $($("#flowName")[0]).val();
    			workFlowData['flowName'] = flowName;
    			console.log(JSON.stringify(workFlowData));
    		});
    		
    		// 装载流程
    		$("#btnLoad").click(function(){
    			event.preventDefault();
    			clearFlow();
    			var value = $("#flowObj").val();
    			if ($.trim(value) == "") {
        			alert("error");
    				return;
    			}
    			var data = $.parseJSON($("#flowObj").val());
    			loadFlow(data);
    		});
    		
    		// 获取流程节点；
    		function getEndPoints() {
    			var points = $("#statemachine-demo .w");
    			var resultEndPoints = [];
    			for (var i = 0; i < points.length; i++) {
    				var pointData = {};
    				pointData["id"]   = $(points[i]).attr("id");
    				pointData["left"] = $(points[i]).css("left");
    				pointData["top"]  = $(points[i]).css("top");
    				resultEndPoints.push(pointData);
    			}
    			return resultEndPoints;
    		}
    		
    		// 获取节点关联；
    		function getConnections() {
    			var resultContions = [];
    			var all = firstInstance.getAllConnections();
    			for (var i = 0; i < all.length; i++) {
    				var connection = {};
    				connection['sourceId'] = all[i].sourceId;
    				connection['targetId'] = all[i].targetId;
    				resultContions.push(connection);
    			}
    			return resultContions;
    		}
    		
    		// 创建一个实例
    		function getInstance() {
    			firstInstance = jsPlumb.getInstance({
    		        Endpoint: ["Dot", {radius: 1}],
    		        HoverPaintStyle: {strokeStyle: "#1e8151", lineWidth: 2 },
    		        ConnectionOverlays: [
    		            [ "Arrow", {
    		                location: 1,
    		                id: "arrow",
    		                length: 14,
    		                foldback: 0.8
    		            } ],
    		            [ "Label", { label: "", id: "label", cssClass: "aLabel" }]
    		        ],
    		        Container: "statemachine-demo"
    		    });
        		// 双击断开连接；
    		    firstInstance.bind("click", function (c) {
    		        firstInstance.detach(c);
    		    });
        		return firstInstance;
    		}
    		
    		// 清空流程区域
    		function clearFlow() {
    			window.id = 1;
    			firstInstance.reset();
    			firstInstance = null;
        		firstInstance = getInstance();
    			$("#statemachine-demo .w").each(function() {
    				this.remove();
    			})
    		}
    		
    		// 加载流程
    		function loadFlow(data) {    			
    			for (i in data['endPoints']) {
    				eulerCreateEndPoint(firstInstance, data['endPoints'][i]);
    				window.id++;
    			}
    			
    			for (i in data['contions']) {
    				eulerCreateConnect(firstInstance, data['contions'][i]);
    			}
    		}
        	//设置 组件单击可以修改名称；
        	function editable(el) {
        		el.click(function(){
        			me = this;
        			console.log();
        			var tmp = $("<input />");
        			tmp.css("position", "absolute");
        			tmp.css("z-index", "5");
        			tmp.css("left", $(this).position().left + 40);
        			tmp.css("top", $(this).position().top + 40);
        			$(tmp).val($(me).find("span").text());
        			tmp.focusout(function(){
        				$(me).find("span").text($(tmp).val());
        				$(tmp).remove();
        			});
        			tmp.appendTo("#statemachine-demo");
        			tmp.focus()
        		})
        	}
        	
        	//设置 组件双击可以删除；
        	function removable(el) {
        		el.dblclick(function(){
        			$("#statemachine-demo input").each(function(){
        				$(this).remove();
        			})
					this.remove();
        		})
        	}
    	});
    </script>
</body>
</html>